
/*
 * URIResourceIDDialog.java
 *
 * Created on 16-mag-2011, 12.49.55
 */
package it.txt.access.capability.spi.resource.http.dialog;

import it.txt.access.capability.spi.resource.http.model.HTTPResourceIDModel;
import it.txt.access.capability.spi.resource.http.model.ValidationException;
import it.txt.access.capability.spi.resource.model.ICapabilityResourceIDModel;
import it.txt.access.capability.spi.resource.visual.ICapabilityResourceIDDialog;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author seccia
 * @author Salvatore Piccione (salvatore.piccione AT txtgroup DOT com)
 */
public class HTTPResourceIDDialog extends ICapabilityResourceIDDialog {
    
    private static final long serialVersionUID = -8665363973946265973L;
    
    private StringBuilder errorMessage;
    private HTTPResourceIDModel model;
    
    /** Creates new form URIResourceIDDialog */
    public HTTPResourceIDDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setTitle("Capability :: Plugin :: Resource :: HTTP");
        addFieldContentUpdateListener(host_txt);
        addFieldContentUpdateListener(whole_uri_txt);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        kind_of_http_uri = new javax.swing.ButtonGroup();
        cancelButton = new javax.swing.JButton();
        main_namel = new javax.swing.JPanel();
        scheme_lbl = new javax.swing.JLabel();
        host_lbl = new javax.swing.JLabel();
        host_txt = new javax.swing.JTextField();
        path_lbl = new javax.swing.JLabel();
        path_txt = new javax.swing.JTextField();
        query_lbl = new javax.swing.JLabel();
        query_txt = new javax.swing.JTextField();
        scheme_cmb = new javax.swing.JComboBox();
        port_lbl = new javax.swing.JLabel();
        port_txt = new javax.swing.JTextField();
        fragment_lbl = new javax.swing.JLabel();
        fragment_txt = new javax.swing.JTextField();
        whole_uri_rbt = new javax.swing.JRadioButton();
        whole_uri_txt = new javax.swing.JTextField();
        uri_parts_rbt = new javax.swing.JRadioButton();
        jSeparator1 = new javax.swing.JSeparator();
        okButton = new javax.swing.JButton();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        main_namel.setBorder(javax.swing.BorderFactory.createTitledBorder("HTTP(S) Resource URI"));
        main_namel.setPreferredSize(new java.awt.Dimension(449, 230));

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("resource-bundles/form-labels"); // NOI18N
        scheme_lbl.setText(bundle.getString("scheme_lbl")); // NOI18N

        host_lbl.setText(bundle.getString("host_lbl")); // NOI18N

        host_txt.setEditable(false);
        host_txt.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0)));
        host_txt.setName(bundle.getString("host_lbl")); // NOI18N
        host_txt.setPreferredSize(new java.awt.Dimension(200, 20));

        path_lbl.setText(bundle.getString("path_lbl")); // NOI18N

        path_txt.setEditable(false);
        path_txt.setName(bundle.getString("path_lbl")); // NOI18N

        query_lbl.setText(bundle.getString("query_lbl")); // NOI18N

        query_txt.setEditable(false);
        query_txt.setName(bundle.getString("query_lbl")); // NOI18N

        scheme_cmb.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "http", "https" }));
        scheme_cmb.setEnabled(false);
        scheme_cmb.setName(bundle.getString("scheme_lbl")); // NOI18N

        port_lbl.setText(bundle.getString("port_lbl")); // NOI18N

        port_txt.setEditable(false);
        port_txt.setName(bundle.getString("port_lbl")); // NOI18N

        fragment_lbl.setText(bundle.getString("fragment_lbl")); // NOI18N

        fragment_txt.setEditable(false);
        fragment_txt.setName(bundle.getString("fragment_lbl")); // NOI18N

        kind_of_http_uri.add(whole_uri_rbt);
        whole_uri_rbt.setSelected(true);
        whole_uri_rbt.setText(bundle.getString("whole_uri_rbt")); // NOI18N
        whole_uri_rbt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                whole_uri_rbtActionPerformed(evt);
            }
        });

        whole_uri_txt.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0)));
        whole_uri_txt.setName(bundle.getString("whole_uri_rbt")); // NOI18N
        whole_uri_txt.setPreferredSize(new java.awt.Dimension(200, 20));

        kind_of_http_uri.add(uri_parts_rbt);
        uri_parts_rbt.setText(bundle.getString("uri_parts_rbt")); // NOI18N
        uri_parts_rbt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uri_parts_rbtActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout main_namelLayout = new javax.swing.GroupLayout(main_namel);
        main_namel.setLayout(main_namelLayout);
        main_namelLayout.setHorizontalGroup(
            main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(main_namelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(main_namelLayout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addGroup(main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(path_lbl)
                            .addComponent(query_lbl)
                            .addComponent(host_lbl)
                            .addComponent(scheme_lbl)
                            .addComponent(port_lbl)
                            .addComponent(fragment_lbl))
                        .addGap(18, 18, 18)
                        .addGroup(main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(fragment_txt)
                            .addComponent(port_txt)
                            .addComponent(query_txt, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                            .addComponent(path_txt, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                            .addComponent(scheme_cmb, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(host_txt, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)))
                    .addGroup(main_namelLayout.createSequentialGroup()
                        .addComponent(uri_parts_rbt)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(main_namelLayout.createSequentialGroup()
                        .addComponent(whole_uri_rbt)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(whole_uri_txt, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        main_namelLayout.setVerticalGroup(
            main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(main_namelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(whole_uri_rbt)
                    .addComponent(whole_uri_txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(5, 5, 5)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(uri_parts_rbt)
                .addGap(8, 8, 8)
                .addGroup(main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(scheme_lbl)
                    .addComponent(scheme_cmb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(host_lbl)
                    .addComponent(host_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(port_lbl)
                    .addComponent(port_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(path_lbl)
                    .addComponent(path_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(query_lbl)
                    .addComponent(query_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(main_namelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fragment_lbl)
                    .addComponent(fragment_txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(25, Short.MAX_VALUE))
        );

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(main_namel, javax.swing.GroupLayout.DEFAULT_SIZE, 438, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(main_namel, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(okButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        if (validateForm())
            doClose(RET_OK);
        else {
            JOptionPane.showMessageDialog(this,
                    errorMessage, "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed

    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

    private void whole_uri_rbtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_whole_uri_rbtActionPerformed
        //disable all text field relating to the URI component parts
        scheme_cmb.setEnabled(false);
        host_txt.setEditable(false);
        port_txt.setEditable(false);
        path_txt.setEditable(false);
        query_txt.setEditable(false);
        fragment_txt.setEditable(false);

        //enable the text field to insert the whole URI
        whole_uri_txt.setEditable(true);
    }//GEN-LAST:event_whole_uri_rbtActionPerformed

    private void uri_parts_rbtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uri_parts_rbtActionPerformed
        //enable all text field relating to the URI component parts
        scheme_cmb.setEnabled(true);
        host_txt.setEditable(true);
        port_txt.setEditable(true);
        path_txt.setEditable(true);
        query_txt.setEditable(true);
        fragment_txt.setEditable(true);

        //disable the text field to insert the whole URI
        whole_uri_txt.setEditable(false);
    }//GEN-LAST:event_uri_parts_rbtActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel fragment_lbl;
    private javax.swing.JTextField fragment_txt;
    private javax.swing.JLabel host_lbl;
    private javax.swing.JTextField host_txt;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.ButtonGroup kind_of_http_uri;
    private javax.swing.JPanel main_namel;
    private javax.swing.JButton okButton;
    private javax.swing.JLabel path_lbl;
    private javax.swing.JTextField path_txt;
    private javax.swing.JLabel port_lbl;
    private javax.swing.JTextField port_txt;
    private javax.swing.JLabel query_lbl;
    private javax.swing.JTextField query_txt;
    private javax.swing.JComboBox scheme_cmb;
    private javax.swing.JLabel scheme_lbl;
    private javax.swing.JRadioButton uri_parts_rbt;
    private javax.swing.JRadioButton whole_uri_rbt;
    private javax.swing.JTextField whole_uri_txt;
    // End of variables declaration//GEN-END:variables

    @Override
    public ICapabilityResourceIDModel getModel() {
        return model;
    }
    
    private void addFieldContentUpdateListener(final javax.swing.JTextField textBox) {

        textBox.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                hihglightFieldBorder(e);
            }

            public void removeUpdate(DocumentEvent e) {
                hihglightFieldBorder(e);
            }

            public void changedUpdate(DocumentEvent e) {
                hihglightFieldBorder(e);
            }

            private void hihglightFieldBorder(DocumentEvent e) {
                if (textBox.getText().equals("")) {
                    textBox.setBorder(
                            javax.swing.BorderFactory.createLineBorder(
                            new java.awt.Color(255, 0, 0)));
                } else {
                    textBox.setBorder(
                            javax.swing.BorderFactory.createLineBorder(
                            new java.awt.Color(0, 0, 0)));
                }
            }
        });
    }
        
    public boolean validateForm() {
        errorMessage = new StringBuilder();
        StringBuilder missingFields = new StringBuilder();
        StringBuilder invalidFields = new StringBuilder();
        HTTPResourceIDModel model = new HTTPResourceIDModel();
        
        if (whole_uri_rbt.isSelected()) {
            if (!isMissingTextField(whole_uri_txt, missingFields)) {
                try {
                    model.setURI(new URI(whole_uri_txt.getText()));
                } catch (URISyntaxException ex) {
                    Logger.getLogger(HTTPResourceIDDialog.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        } else {

            try {
                model.setScheme((String) scheme_cmb.getSelectedItem());
            } catch (ValidationException e) {
                invalidFields.append(scheme_cmb.getName());
                invalidFields.append(" ");
                invalidFields.append(e.getMessage());
            }
            
            if (!isMissingTextField(host_txt, missingFields))
                    model.setHost(host_txt.getText());
            
            //port number validation
            String currentFieldValue = port_txt.getText();
            if (!currentFieldValue.isEmpty()) {
                try {
                    model.setPort(Integer.parseInt(currentFieldValue));
                } catch (NumberFormatException e) {
                    if (invalidFields.length() > 0)
                        invalidFields.append(", ");
                    invalidFields.append(port_txt.getName());
                } catch (ValidationException e) {
                    if (invalidFields.length() > 0)
                        invalidFields.append(", ");
                    invalidFields.append(port_txt.getName());
                    invalidFields.append(" ");
                    invalidFields.append(e.getMessage());
                }
            }
            
            currentFieldValue = path_txt.getText();
            if (!currentFieldValue.isEmpty())
                model.setPath(currentFieldValue);
            
            currentFieldValue = query_txt.getText();
            if (!currentFieldValue.isEmpty())
                model.setQuery(currentFieldValue);
            
            currentFieldValue = fragment_txt.getText();
            if (!currentFieldValue.isEmpty())
                model.setFragment(currentFieldValue);
        }
        
                
        if (missingFields.length() > 0) {
            missingFields.insert(0, "The following fields are empty:\n");
            errorMessage.append(missingFields);
        }
        if (invalidFields.length() > 0) {
            invalidFields.insert(0, "The following fields are not valid:\n");
            if (errorMessage.length() > 0) {
                errorMessage.append("\n").append(invalidFields);
            }
            else
                errorMessage.append(invalidFields);
        }
        if (errorMessage.length() > 0)
            return false;
        else {
            this.model = model;
            return true;
        }
    }
    
    private boolean isMissingTextField (JTextField textBox, StringBuilder missingFieldMessage) {
        if (textBox.getText().equals("")) {
            if (missingFieldMessage.length() > 0)
                missingFieldMessage.append(", ").append(textBox.getName());
            else
                missingFieldMessage.append(textBox.getName());
            return true;
        }
        return false;
    }
}
